package com.halixun.d2app.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.halixun.d2app.R;
import com.halixun.d2app.app.MyApplication;
import com.halixun.d2app.dialog.LoadingFragment;
import com.halixun.d2app.utils.SystemUIUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * @ProjectName: D2App
 * @Package: com.halixun.d2app.base
 * @ClassName: BaseActivity
 * @Description: java类作用描述
 * @Author: hdx
 * @CreateDate: 2019/11/28 17:59
 * @UpdateUser: hdx
 * @UpdateDate: 2019/11/28 17:59
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class BaseActivity extends AppCompatActivity implements View.OnClickListener {
    protected View mBack;

    protected TextView mTitleView;

    private ProgressDialog mProgressDlg;

    protected TextView mComfrm;

    protected View mLine;

    private List<Timer> mTimers;

    private List<TimerTask> mTimerTasks;

    private LoadingFragment mLoadingFragment;

    private final String mLoadingDialogTag = "loadingDialog";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()
                && getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
                && getIntent().getAction() != null
                && getIntent().getAction().equals(Intent.ACTION_MAIN)) {
            finish();
            return;
        }
        mTimers = new ArrayList<>();
        mTimerTasks = new ArrayList<>();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (MyApplication.isSunmi()) {
            SystemUIUtils.setStickFullScreen(getWindow().getDecorView());
        }
    }


    public void setContentView(@LayoutRes int layoutResID) {
        LinearLayout layout = (LinearLayout) View.inflate(this, R.layout.actionbar_applayout, null);
        if (layoutResID != 0) {
            layout.addView(View.inflate(this, layoutResID, null), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        setContentView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mBack = findViewById(R.id.action_button1);
        mComfrm = findViewById(R.id.comfrm);
        mBack.setOnClickListener(this);
        mTitleView = layout.findViewById(R.id.action_text);
        mLine = layout.findViewById(R.id.line);
        ((View) ((ViewGroup) mTitleView.getParent()).getParent()).setPadding(0, getStatusBarHeight(this), 0, 0);
    }

    public void hideActionBar() {
        ((ViewGroup) ((ViewGroup) mTitleView.getParent()).getParent()).setVisibility(View.GONE);
    }

    public void showActionBar() {
        ((ViewGroup) ((ViewGroup) mTitleView.getParent()).getParent()).setVisibility(View.VISIBLE);
    }

    public void setTitle(String title) {
        mTitleView.setText(TextUtils.isEmpty(title) ? "" : title);
    }

    public void setTitle(int title) {
        mTitleView.setText(title);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.action_button1) {
            onBackPressed();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

//    @SuppressLint("NewApi")
//    public void showProgressDialog(String message) {
//        if (mProgressDlg == null && !isFinishing() && !isDestroyed()) {
//            mProgressDlg = new ProgressDialog(this);
//            mProgressDlg.setMessage(message);
//            mProgressDlg.setCanceledOnTouchOutside(false);
//            // mProgressDlg.setCanceledOnTouchOutside(false);
//            // mProgressDlg.setCancelable(false);
//            mProgressDlg.show();
//            Window window = mProgressDlg.getWindow();
//            if (window != null) {
//                WindowManager.LayoutParams mParams = window.getAttributes();
//                if (mParams != null) {
//                    mParams.width = (int) (mParams.width * 0.5);
//                    mParams.gravity = Gravity.CENTER;
//                    mProgressDlg.getWindow().setAttributes(mParams);
//                }
//            }
//        }
//    }


    @SuppressLint("NewApi")
    public void showProgressDialog(String message) {
        LoadingFragment f = (LoadingFragment) getSupportFragmentManager().findFragmentByTag(mLoadingDialogTag);
        if (null == f) {
            mLoadingFragment = LoadingFragment.getInstance(message);
            mLoadingFragment.show(getSupportFragmentManager(), mLoadingDialogTag);
        } else {
            if (null == mLoadingFragment){
                mLoadingFragment = f;
            }
            if (mLoadingFragment.isHidden()){
                mLoadingFragment.setTextMessage(message);
                getSupportFragmentManager().beginTransaction().show(mLoadingFragment);
            } else {
                mLoadingFragment.setTextMessage(message);
            }
        }
    }


    @SuppressLint("NewApi")
    public void setProgressDialogMessage(String message) {
        if (mProgressDlg != null && mProgressDlg.isShowing()) {
            Context context = ((ContextWrapper) mProgressDlg.getContext()).getBaseContext();
            if (context instanceof Activity) {
                if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed())
                    mProgressDlg.setMessage(message);
            } else {
                mProgressDlg.setMessage(message);
            }
        }
    }

//    @SuppressLint("NewApi")
//    public void dismissProgressDialog() {
//        if (mProgressDlg != null && mProgressDlg.isShowing()) {
//            Context context = ((ContextWrapper) mProgressDlg.getContext()).getBaseContext();
//            if (context instanceof Activity) {
//                if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed())
//                    mProgressDlg.dismiss();
//            } else {
//                mProgressDlg.dismiss();
//            }
//        }
//        mProgressDlg = null;
//    }

    @SuppressLint("NewApi")
    public void dismissProgressDialog() {
        LoadingFragment f = (LoadingFragment) getSupportFragmentManager().findFragmentByTag(mLoadingDialogTag);
        if (null != f) {
            f.dismiss();
            f = null;
        }
        mLoadingFragment = null;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }


    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }


    /**
     * 获取安卓顶部状态栏高度
     *
     * @param context
     * @return
     */
    protected int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 获取地步导航栏高度（适配华为）
     *
     * @return
     */
    public int getNavigationBarHeight() {
        boolean hasMenuKey = ViewConfiguration.get(this).hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
        if (!hasMenuKey && !hasBackKey) {
            Resources resources = getResources();
            int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
//获取NavigationBar的高度
            int height = resources.getDimensionPixelSize(resourceId);
            return height;
        } else {
            return 0;
        }
    }


    protected void setFitsSystemWindows(Activity activity, boolean value) {
        ViewGroup contentFrameLayout = (ViewGroup) activity.findViewById(android.R.id.content);
        View parentView = contentFrameLayout.getChildAt(0);
        if (parentView != null && Build.VERSION.SDK_INT >= 14) {
            parentView.setFitsSystemWindows(value);
        }
    }

    /**
     * 添加状态栏占位视图 * * @param activity
     */
    private void addStatusViewWithColor(Activity activity, int color) {
        ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
        View statusBarView = new View(activity);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
        statusBarView.setBackgroundColor(color);
        contentView.addView(statusBarView, lp);
    }


    protected void setImmerseLayout(View view) {// view为标题栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);
        }
    }

    protected void setImmerseLayout2(View view) {// view为标题栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int statusBarHeight = getStatusBarHeight(this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);
        }
    }

    /**
     * 倒计时
     *
     * @param time
     * @param task
     */
    protected Timer countDown(long time, TimerTask task) {
        Timer timer = new Timer();
        timer.schedule(task, time);
        mTimers.add(timer);
        mTimerTasks.add(task);
        return timer;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimers != null && mTimers.size() > 0) {
            for (Timer timer : mTimers) {
                timer.cancel();
            }
            mTimers.clear();
            mTimers = null;
        }
        if (mTimerTasks != null && mTimerTasks.size() > 0) {
            for (TimerTask task : mTimerTasks) {
                task.cancel();
            }
            mTimerTasks.clear();
            mTimerTasks = null;
        }
    }
}
